<template>
  <div class="waitingImp-container">
    <el-tabs v-model="activeTags" type="border-card" @tab-click="changeTable">
      <el-tab-pane label="门诊患者" name="outpatient">
        <page-header
          @add="add(0)"
          ref="phref1"
          :type="pageHeaderTitle"
          @searchChange="searchData"
          @reset="resetSeach"
          :start="day"
          :end="day"
        >
          <template v-slot:select3>
            <xm-remote-select
              v-model="select3"
              :itemList="dt.itemList"
              @loadData="dtLoad"
            ></xm-remote-select>
          </template>
        </page-header>
        <div class="patient-content">
          <wait-patient-card
            v-for="(item, index) in pageData.listData"
            :key="index"
            :item="item"
            @select="cardSelect"
          ></wait-patient-card>
          <div
            style="width: 100%; text-align: center"
            v-if="pageData.listData.length === 0"
          >
            暂无数据
          </div>
        </div>
        <xm-pagination
          ref="xmp1"
          style="bottom: 5px; position: relative"
          :total="pageData.total"
          :defaultSize="pageData.search.pageSize"
          @pagination="paginaChange"
        ></xm-pagination>
      </el-tab-pane>
      <el-tab-pane label="住院患者" name="hospitalization">
        <page-header
          @add="add(1)"
          ref="phref2"
          :type="pageHeaderTitle"
          @searchChange="searchData"
          @reset="resetSeach"
          :start="day"
          :end="day"
        >
          <template v-slot:select3>
            <xm-remote-select
              v-model="select3"
              :itemList="dt.itemList"
              @loadData="dtLoad"
            ></xm-remote-select>
          </template>
        </page-header>
        <div class="patient-content">
          <wait-patient-card
            v-for="(item, index) in pageData.listData"
            :key="index"
            :item="item"
            @select="cardSelect"
          ></wait-patient-card>
          <div
            style="width: 100%; text-align: center"
            v-if="pageData.listData.length === 0"
          >
            暂无数据
          </div>
        </div>
        <xm-pagination
          ref="xmp2"
          style="bottom: 5px; position: relative"
          :total="pageData.total"
          :defaultSize="pageData.search.pageSize"
          @pagination="paginaChange"
        ></xm-pagination>
      </el-tab-pane>
    </el-tabs>
    <add-patient
      ref="addRef"
      :title="pageData.title"
      @success="addSucess"
    ></add-patient>
  </div>
</template>
<script>
  import { ref, reactive, onActivated } from 'vue'
  import PageHeader from '@/components/PageHeader'
  import waitPatientCard from './components/waitPatientCard'
  import AddPatient from '@/components/AddPatient'
  import XmPagination from 'XMC/XmPagination'
  import { awaitPatients } from '@/api/modules/patient.js'
  import { searchWaitRiskPatientList } from '@/api/modules/risk.js'
  import { useRouteAndRouter } from '@/hooks/core/useRouteAndRouter.js'
  import { usePromise } from '@/hooks/core/usePromise.js'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { modifyVisit } from '@/api/modules/patient'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated.js'
  import XmRemoteSelect from 'XMC/XmRemoteSelect'
  import { useStore } from 'vuex'
  import moment from 'moment'
  import { computed } from '@vue/reactivity'

  export default {
    // 待诊患者
    name: 'waitingImp',
    components: {
      waitPatientCard,
      AddPatient,
      PageHeader,
      XmPagination,
      XmRemoteSelect,
    },
    setup() {
      const activeTags = ref('outpatient')

      const day = moment().locale('zh-cn').format('YYYY-MM-DD')
      const pageData = reactive({
        listData: [],
        total: null,
        search: {
          pageIndex: 1,
          pageSize: 10,
          type: 0,
          startDay: day,
          endDay: day,
          status: null,
        },
        title: '新增患者',
      })

      const addRef = ref(null)
      const add = function (type) {
        pageData.title = '新增患者'
        addRef.value.init({ type })
      }
      const cardSelect = function (dic) {
        if (dic.key === 1) {
          pageData.title = '修改患者科室'
          addRef.value.init({
            id: dic.value,
            type: pageData.search.type,
            edit: dic.key,
            historicalVisitId: dic.historicalVisitId,
          })
        } else if (dic.key === 2) {
          pageData.title = '快速接诊'
          addRef.value.init({ id: dic.value, quickReceptionType: 2 })
        } else {
          const historicalVisitId = dic.historicalVisitId
          if (!historicalVisitId) return
          ElMessageBox.confirm(
            '是否结束当前就诊，注意：不会主动改变病历状态',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          ).then(async () => {
            const params = { historicalVisitId, status: 3 }
            const res = await modifyVisit(params)
            if (!res || res.code !== '0000') return
            ElMessage({
              type: 'success',
              message: '结束就诊成功',
            })
            loadData(pageData.search)
          })
        }
      }
      // 加载方法
      const { to } = usePromise()
      const { isRisk } = useRouteAndRouter()
      const risk = isRisk()
      const loadData = async function (params) {
        function toLoad(params) {
          if (risk) {
            return to(searchWaitRiskPatientList(params))
          } else {
            return to(awaitPatients(params))
          }
        }
        const [err, res] = await toLoad(params)
        if (err) return
        pageData.listData = res.data ? res.data : []
        pageData.total = res.total
        // const res = await awaitPatients(params)
        // pageData.listData = res.data ? res.data : []
        // pageData.total = res.total
      }

      const pageHeaderTitle = risk ? 'waitingRiskImp' : 'waitingImp'
      const addSucess = async function () {
        loadData(pageData.search)
      }
      // 事件处理
      const resetSeach = function () {
        select3.value = null
        pageData.search = {
          pageIndex: 1,
          pageSize: 10,
          type: pageData.search.type,
          startDay: day,
          endDay: day,
          status: null,
        }
        loadData(pageData.search)
      }
      const searchData = function (params) {
        console.log('params =' + JSON.stringify(params))
        pageData.search.startDay = params.value2.start
          ? moment(params.value2.start).format('YYYY-MM-DD')
          : null
        pageData.search.endDay = params.value2.end
          ? moment(params.value2.end).format('YYYY-MM-DD')
          : null
        pageData.search.departmentId = select3.value
        pageData.search.code = params.value4
        pageData.search.status = params.value6
        loadData(pageData.search)
      }
      const paginaChange = function (params) {
        pageData.search.pageIndex = params.current
        pageData.search.pageSize = params.pageSize
        loadData(pageData.search)
      }

      onMountedOrActivated(() => {
        loadData(pageData.search)
      })

      const phref1 = ref(null)
      const phref2 = ref(null)
      const xmp1 = ref(null)
      const xmp2 = ref(null)
      const changeTable = function () {
        if (activeTags.value === 'outpatient') {
          pageData.search.type = 0
          pageData.search = {
            pageIndex: 1,
            pageSize: 10,
            type: 0,
            startDay: day,
            endDay: day,
            status: null,
          }
          xmp1.value.reset()
          phref1.value.reset()
        } else {
          pageData.search.type = 1
          pageData.search = {
            pageIndex: 1,
            pageSize: 10,
            type: 1,
            startDay: day,
            endDay: day,
            status: null,
          }
          xmp2.value.reset()
          phref2.value.reset()
        }
      }

      const dt = reactive({ itemList: [] })
      const select3 = ref(null)
      const store = useStore()
      const dtLoad = async function (cb) {
        dt.itemList = await store.dispatch('presetData/getDepartmentList')
        // const search = { pageIndex: 1, pageSize: 500, status: 1 }
        // const res = await departments(search)
        // dt.itemList = res.data.map((item) => {
        //   return { value: item.id, label: item.name }
        // })
        cb()
      }
      return {
        activeTags,
        add,
        pageData,
        cardSelect,
        addRef,
        paginaChange,
        addSucess,
        changeTable,
        searchData,
        resetSeach,
        day,
        phref2,
        phref1,
        xmp1,
        xmp2,
        dtLoad,
        dt,
        select3,
        pageHeaderTitle,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .waitingImp-container {
    padding: 32px;
    .el-tabs {
      overflow: hidden;
      background-color: white;
      min-height: calc(100vh - 112px);
      .el-divider--horizontal {
        margin: 12px 2px;
      }
      .patient-content {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-content: flex-start;
        min-height: calc(100vh - 400px);
      }
    }
  }
</style>
